import network
from machine import Pin
import time
import ubinascii
from umqtt.simple import MQTTClient
from machine import Timer

# WiFi 信息
WIFI_SSID = "Redmi_cmcc"
WIFI_PASSWORD = "64992151"

light = Pin(2, Pin.OUT)

# 巴法 MQTT 服务器信息
MQTT_SERVER = "bemfa.com"
MQTT_PORT = 9501

# 替换为你的私钥（UID）
CLIENT_ID = "be676fa03fac421fb19fea2ab4f15688"
TOPIC1 = "catbox006"
TOPIC2 = "clear006"
TOPIC3 = "openfan003"
TOPIC4 = "timer006"  
TOPIC5 = "manual006"  
TOPIC6 = "auto006"  

# 修改mqtt.py，添加全局变量存储回调函数
change_callback = None

client = None

def connect_wifi():
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('正在连接到网络...')
        sta_if.active(True)
        sta_if.connect(WIFI_SSID, WIFI_PASSWORD)
        max_wait = 10  # 最大等待时间为 10 秒
        while max_wait > 0:
            if sta_if.isconnected():
                print('网络配置信息:', sta_if.ifconfig())
                break
            max_wait -= 1
            time.sleep(1)  # 每次循环等待 1 秒
        if not sta_if.isconnected():
            print('无法连接到网络')
            return False
    

def sub_cb(topic, msg,change_variable_callback):
    print('在主题 %s 上收到消息: %s' % (topic, msg))
    msg_str = msg.decode()
    topic_str = topic.decode()
    change_variable_callback(topic_str, msg_str)
    
def connect_and_subscribe():
    global client, change_callback
    client = MQTTClient(CLIENT_ID, MQTT_SERVER, MQTT_PORT)
    client.set_callback(lambda topic, msg: sub_cb(topic, msg, change_callback))
    client.connect()
    client.subscribe(TOPIC1, qos=0)
    client.subscribe(TOPIC2, qos=0)
    client.subscribe(TOPIC3, qos=0)
    client.subscribe(TOPIC4, qos=0)  
    client.subscribe(TOPIC5, qos=0)  
    client.subscribe(TOPIC6, qos=0)  
    print('已连接到 %s MQTT 代理，订阅了主题' % (MQTT_SERVER))

def check_mqtt_msg(timer):
    global client
    try:
        client.check_msg()
        client.ping()
    except OSError as e:
        if e.errno == 128:  # 检查是否是连接断开错误
            print('连接已断开，尝试重新连接...')
            try:
                connect_wifi()  # 确保网络连接正常
                connect_and_subscribe()  # 重新连接到 MQTT 服务器
            except OSError as reconnect_error:
                print('重新连接 MQTT 代理时出错: %s' % reconnect_error)
        else:
            print('检查 MQTT 消息时出错: %s' % e)

def start_mqtt(change_variable_callback):
    global change_callback
    change_callback = change_variable_callback  # 存储回调函数
    connect_wifi()
    try:
        connect_and_subscribe()
    except OSError as e:
        print('无法连接到 MQTT 代理: %s' % e)
        return

    # 创建定时器，每 1000 毫秒（1 秒）调用一次 check_mqtt_msg 函数
    timer = Timer(0)
    timer.init(period=1000, mode=Timer.PERIODIC, callback=check_mqtt_msg)
    
def test(topic, msg):
    print('在主题 %s 上收到消息: %s' % (topic, msg))
    if msg=='on':
        light.on()
    if msg=='off':
        light.off()
        
if __name__ == "__main__":
    start_mqtt(test)